<template>
	<!--本文件由FirstUI授权予向*磊（会员ID：3 7  89）专用，请尊重知识产权，勿私下传播，违者追究法律责任。-->
	<fui-index-list isSrc :listData="records" @init="init" @click="itemClick">
		<fui-search-bar @search="search"></fui-search-bar>
		<fui-filter-bar :items="items" @change="changeItem"></fui-filter-bar>
		<template v-slot:footer>
			<fui-loadmore v-if="!show"></fui-loadmore>
			<fui-divider :text="recordsNum" v-if="show"></fui-divider>
		</template>
		<fui-actionsheet :show="showAc" :tips="tips" :itemList="itemList" @click="itemAcClick"
			@cancel="cancel"></fui-actionsheet>

		<!-- 类型选择 -->
		<fui-picker :options="optionsType" :show="showType" @change="changeType" @cancel="cancelType"></fui-picker>
		<!-- 区域选择 -->
		<fui-picker linkage :layer="2" :options="options" :show="showArea" @change="changeArea"
			@cancel="cancelArea"></fui-picker>
	</fui-index-list>
</template>

<script>
	import lists from './index.list.js'
	import area from '@/area/provinces.json'
	import regionUtils from "@/utils/regionUtils";
	export default {
		data() {
			return {
				//如果是请求数据返回，返回后直接整体赋值给lists（注意数据格式正确）
				lists: lists,
				show: false,
				showAc: false,
				tips: '退出后不会删除任何历史数据，下次登录依然可以使用本账号。',
				itemList: [{
					text: '退出登录',
					color: '#FF2B2B'
				}],
				user: {},
				records: [],
				recordsNum: 0,
				legalSpecialtyMap: {},
				name: '',
				objId: '',
				optionsType: ['7:00-8:30', '8:30-10:00', '10:00-11:30', '2:00-3:30', '3:30-5:00'],
				items: [{
					text: '全国',
					value: '',
					type: 'filter',
					active: false
				}, {
					text: '类型',
					value: '',
					type: 'filter'
				}],
				showType: false,
				showArea: false,
				options: area,
				practiceRegion: '',
				menuList: [],
			}
		},
		onLoad(e) {
			this.objId = String(e._id) || 0;
		},
		created() {
			// this.fetchLegalSpecialtyMap()
			this.getLawyers()
			this.getLegalCategories()
		},
		methods: {
			changeArea(e) {
				this.showArea = false
				console.log(e)
				console.log('选择区域：' + e.value[1])
				this.practiceRegion = e.value[1]
				// 修改 items 中第一个对象的 text
				if (this.items && this.items.length > 0) {
					this.items[0].text = e.result || '全国'; // 如果 e.value[1] 为空，默认显示 "全国"
				}
				this.getLawyers()
			},
			cancelArea() {
				this.showArea = false
				this.items[0].text = '全国';
				this.practiceRegion = ''
				this.getLawyers()
			},
			changeType(e) {
				this.showType = false
				if (this.items && this.items.length > 0) {
					this.items[1].text = e.result || '类型'; // 如果 e.value[1] 为空，默认显示 "全国"
				}
				console.log(this.menuList)
				console.log(e.result)
				const selectedItem = this.menuList.find(item => item.name === e.result);
				console.log(selectedItem, selectedItem)
				if (selectedItem) {
					this.objId = selectedItem.id
				} else {
					this.objId = ''
				}
				this.getLawyers()
			},
			cancelType() {
				this.showType = false
				this.items[0].text = '类型';
				this.objId = ''
				this.getLawyers()
			},
			changeItem(e) {
				if (e.index == 0) {
					this.showArea = true
				} else if (e.index == 1) {
					this.showType = true
				}
			},
			async getLegalCategories() {
				try {
					// 查询 legal-categories 数据库
					const res = await uniCloud.database().collection('legal-categories').get();
					let arr = res.result.data
					if (arr.length > 0) {
						// 将数据分成两个数组
						this.optionsType = arr.map(item => item.name);
						this.menuList = arr.map(item => ({
							name: item.name,
							id: item._id
						}));
					} else {
						this.optionsType = []
					}
				} catch (error) {
					console.error('查询 legal-categories 失败:', error);
				}
			},
			async fetchLegalSpecialtyMap() {
				try {
					const db = uniCloud.database();
					const res = await db.collection("legal-categories").get();
					// 构建映射关系
					this.legalSpecialtyMap = res.result.data.reduce((map, item) => {
						map[item._id] = item.name;
						return map;
					}, {});
				} catch (err) {
					console.error("Error fetching legal specialties:", err);
				}
			},
			// 翻译方法
			translateLegalSpecialty(values) {
				if (!Array.isArray(values)) {
					console.error("Expected an array, but got:", values);
					return ["未知专长"]; // 返回一个数组，默认值为包含“未知专长”的数组
				}
				return values.map(value => this.legalSpecialtyMap[value] || "未知专长");
			},
			async getLawyers() {
				try {
					// 构造查询条件
					const collection = uniCloud.database().collection('lawyers');
					let query = collection;

					// 如果提供了 lawyer_name，添加该条件
					if (this.name) {
						query = query.where({
							lawyer_name: new RegExp(this.name, 'i')
						});
					}
					// 构造一个条件对象
					let conditions = {};

					// 如果存在 practiceRegion，则添加筛选条件
					if (this.practiceRegion) {
						console.log('新增查询条件');
						conditions.practice_region = this.practiceRegion;
					}

					// 如果提供了 legal_specialty（objId），添加该条件
					if (this.objId && this.objId !== 'undefined') {
						if (Array.isArray(this.objId)) {
							// 如果 objId 是一个数组
							conditions.legal_specialty = uniCloud.database().command.in(this.objId);
						} else {
							// 如果 objId 是单个值
							conditions.legal_specialty = uniCloud.database().command.in([this.objId]);
						}
					}

					// 将所有条件一起应用到查询中
					if (Object.keys(conditions).length > 0) {
						query = query.where(conditions);
					};
					console.log('查询条件')
					console.log(query)
					// 查询数据
					const res = await query.get();
					let arr = res.result.data
					if (arr.length) {
						this.recordsNum = arr.length
						this.records = arr;
						await this.rebuildRecords()
						const grouped = await this
							.groupRecordsBySpecialty(); // 等待分组结果
						this.records = Object.entries(grouped).map(([practice_region, data]) => ({
							letter: this.getRegionDisplay(practice_region).charAt(0),
							descr: this.getRegionDisplay(practice_region),
							data
						}));
						await this.constructRecordsFromFavorites();
					} else {
						this.records = []
						console.log('查询失败，没有结果:', res);
					}
				} catch (error) {
					this.records = []
					console.error('查询 lawyers 数据库失败:', error);
				}
			},
			getRegionDisplay(regionCode) {
				return regionUtils.getRegionDisplay(area, regionCode);
			},
			// 获取收藏用户列表并重新构造 records
			async constructRecordsFromFavorites() {
				const favorites = await this.getFavorites(); // 获取收藏用户列表
				if (!Array.isArray(favorites)) {
					console.error("收藏列表不是数组：", favorites);
					return;
				}
				// 构造符合目标结构的数组
				const records = {
					letter: "★", // 默认设置为 "收藏"
					descr: '★ 收藏', // 完整的 practice_region
					data: favorites
				}
				this.records = [records, ...this.records]; // 使用扩展运算符
			},
			async rebuildRecords() {
				this.records = this.records.map(record => ({
					id: record._id, // 保留 text 字段
					text: record.lawyer_name, // 保留 text 字段
					src: record.personal_photo.path, // 保留 src 字段
					practice_region: record.practice_region, // 保留 practice_region 字段
					lawyer_intro: record.lawyer_intro // 保留 practice_region 字段
				}));
			},
			//  分组
			async groupRecordsBySpecialty() {
				const grouped = this.records.reduce((acc, record) => {
					const key = record.practice_region; // 使用 specialty 作为分组的键
					if (!acc[key]) {
						acc[key] = []; // 如果没有这个分组，初始化为空数组
					}
					acc[key].push(record); // 将当前记录加入对应分组
					return acc;
				}, {});
				return grouped
			},
			init() {
				this.show = true;
			},
			// 从收藏中移除
			async removeFromFavorites(userId) {
				let favorites = await this.getFavorites();
				// 过滤掉要移除的用户
				favorites = favorites.filter(fav => fav.id !== userId);
				// 保存更新后的收藏列表到 localStorage
				uni.setStorage({
					key: "favorites",
					data: favorites
				});
				this.fui.toast("取消收藏成功");
			},
			search(e) {
				this.name = e.detail.value
				this.getLawyers()
			},
			async refreshPage() {
				const currentPage = getCurrentPages().pop(); // 获取当前页面实例
				const route = `/${currentPage.route}`; // 当前页面路径
				const options = currentPage.options; // 页面参数

				// 构造完整路径（带参数）
				const queryString = Object.keys(options)
					.map(key => `${key}=${options[key]}`)
					.join('&');

				const fullPath = queryString ? `${route}?${queryString}` : route;

				// 跳转到当前页面，重新加载
				uni.redirectTo({
					url: fullPath
				});
			},
			async itemClick(e) {
				this.user = e;
				this.tips = '';
				this.isCancel = true;
				// 获取收藏列表
				const favorites = await this.getFavorites();

				// 检查是否已收藏
				const isAlreadyFavorited = favorites.some(fav => fav.id === e.id);

				// 动态设置菜单项
				this.itemList = isAlreadyFavorited ? ['查看', '取消收藏'] : ['查看', '收藏'];
				this.theme = 'dark'
				setTimeout(() => {
					this.showAc = true
				}, 50)
			},
			async itemAcClick(e) {
				if (e.text == '查看') {
					this.fui.href("/pages/law/skeleton/skeleton?index=2&_id=" + this.user.id)
				} else if (e.text == '取消收藏') {
					await this.removeFromFavorites(this.user.id)
					await this.refreshPage();
				} else {
					this.fui.toast('收藏成功')
					await this.addToFavorites(this.user)
					await this.refreshPage();
				}
				this.cancel()
			},
			async addToFavorites(user) {
				// 从 localStorage 获取已收藏的用户列表
				let favorites = await this.getFavorites(); // 获取已有收藏列表
				// 检查用户是否已存在，避免重复收藏
				const isAlreadyFavorited = favorites.some(fav => fav.id === user.id);

				if (!isAlreadyFavorited) {
					// 添加当前用户到收藏数组
					favorites.push(user);
					// 保存回 localStorage
					uni.setStorage({
						key: "favorites",
						data: favorites
					});;
					this.$forceUpdate();
				} else {
					this.fui.toast("该用户已收藏");
				}
			},
			// 获取收藏的用户列表
			async getFavorites() {
				try {
					const result = await new Promise((resolve, reject) => {
						uni.getStorage({
							key: "favorites",
							success(e) {
								resolve(e.data || []); // 返回存储的数据，或者空数组
							},
							fail() {
								resolve([]); // 如果没有存储数据，返回空数组
							}
						});
					});
					return result;
				} catch (error) {
					console.error("获取收藏列表失败:", error);
					return []; // 如果发生错误，返回空数组
				}
			},
			cancel() {
				this.showAc = false
			}
		}
	}
</script>

<style>
	page {
		font-weight: normal;
	}
</style>